﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Xts
{
    namespace IceRuntime
    {
        public class XIntermediarySubscriber : XStormBase
        {
            public XIntermediarySubscriber(ref Ice.Communicator ic, ref Ice.Logger logger)
                :base(ic, logger)
            {
            }

            bool Subscribe(string topicName, string monitorDsb)
            {
                IceStorm.TopicPrx topicPrx = RetrieveTopic(topicName);
                if (topicPrx == null)
                {
                    x_logger.error(topicName + " can't be retrieved");
                    return false;
                }

                try
                {
                    Ice.ObjectPrx subPrx = x_ic.stringToProxy(monitorDsb);
                    topicPrx.subscribeAndGetPublisher(x_qos, subPrx);
                    return true;
                }
                catch(IceStorm.AlreadySubscribed)
                {
                    x_logger.error(topicName + ": Already Subscribed.");
                }
                catch (Ice.Exception ex)
                {
                    x_logger.error(ex.Message);
                }
                return false;
            }

            bool Unsubscribe(string topicName, string monitorDsb)
            {
                IceStorm.TopicPrx topicPrx = RetrieveTopic(topicName);
                if (topicPrx == null)
                {
                    x_logger.error(topicName + " can't be retrieved");
                    return false;
                }

                try
                {
                    Ice.ObjectPrx subPrx = x_ic.stringToProxy(monitorDsb);
                    topicPrx.unsubscribe(subPrx);
                    return true;
                }
                catch (IceStorm.NoSuchTopic)
                {
                    x_logger.error(topicName + " is not exist. Can't unsubscribe.");
                }
                catch (Ice.Exception ex)
                {
                    x_logger.error(ex.Message);
                }               

                return false;
            }

            bool RetrievePublishPrx(string topicName, out Ice.ObjectPrx publisherPrx)
            {
                publisherPrx = null;
                IceStorm.TopicPrx topicPrx = RetrieveTopic(topicName);
                if (topicPrx == null)
                {
                    x_logger.error(topicName + " can't be retrieved");
                    return false;
                }

                try
                {
                    publisherPrx = topicPrx.getPublisher();
                    return true;
                }
                catch (Ice.Exception ex)
                {
                    x_logger.error(ex.Message);
                } 
                return false;
            }
        }
    }
}
